package vashion.azeroth.activity.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import vashion.azeroth.contant.CommonErrorEnum;
import vashion.azeroth.core.activity.*;
import vashion.azeroth.core.activity.dao.GlobalActivityExtendInfoDAO;
import vashion.azeroth.core.activity.dao.GlobalActivityInfoDAO;
import vashion.azeroth.core.activity.query.ActivityExtendQueryDO;
import vashion.azeroth.core.activity.query.ActivityInfoQueryDO;
import vashion.azeroth.core.common.NeedOperateFlow;
import vashion.azeroth.core.dao.BaseDao;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.query.ItemQueryDO;
import vashion.azeroth.core.manager.impl.BaseManagerImpl;
import vashion.azeroth.core.manager.item.ItemReadManger;
import vashion.azeroth.core.pojo.common.OperateFlowEnum;
import vashion.azeroth.core.result.ApiResult;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 活动管理
 * <p/>
 * 创建时间: 2014-06-17
 */
@Service
public class GlobalActivityInfoManager extends BaseManagerImpl<GlobalActivityInfoDO> {

    final static Logger logger = LoggerFactory.getLogger(GlobalActivityInfoManager.class);

    @Autowired
    private GlobalActivityInfoDAO globalActivityInfoDAO;

    @Autowired
    private GlobalActivityExtendInfoDAO globalActivityExtendInfoDAO;
    @Resource
    private ItemReadManger itemReadManger;

    public GlobalActivityInfoDO queryActivityInfoById(long activityId) {
        GlobalActivityInfoDO globalActivityInfoDO = null;
        try {
            globalActivityInfoDO = globalActivityInfoDAO.get(activityId);
        } catch (Exception e) {
            logger.error("error", e);
        }
        return globalActivityInfoDO;
    }

    @NeedOperateFlow(operateIdArgLocation = 2, operateFlowEnum = OperateFlowEnum.ACTIVITY)
    public long createGlobalActivity(GlobalActivityInfoDO globalActivityInfoDO, Long loginUserId) {
        long activityId = 0l;
        try {
            Date date = new Date();
            globalActivityInfoDO.setGmtCreate(date);
            globalActivityInfoDO.setGmtModified(date);
            activityId = globalActivityInfoDAO.save(globalActivityInfoDO);
        } catch (Exception e) {
            logger.error("globalActivityInfoDAO.insertGlobalActivityInfo error,", e);
        }
        return activityId;
    }

    public ApiResult<List<GlobalActivityInfoDO>> queryAllActivityByType(ActivityInfoQueryDO activityInfoQueryDO) {
        int totalCount = 0;
        try {
            totalCount = globalActivityInfoDAO.queryCountAllActivityByType(activityInfoQueryDO);
        } catch (Exception e) {
            logger.error("globalActivityInfoDAO.queryCountAllActivityByType error", e);
            return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(), CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
        ApiResult<List<GlobalActivityInfoDO>> result = new ApiResult<List<GlobalActivityInfoDO>>();
        result.setTotalCount(totalCount);
        List<GlobalActivityInfoDO> resourceList = null;
        try {
            activityInfoQueryDO.setStart((activityInfoQueryDO.getPageNO() - 1) * activityInfoQueryDO.getPageSize());
            resourceList = globalActivityInfoDAO.queryAllActivityByType(activityInfoQueryDO);
        } catch (Exception e) {
            logger.error("globalActivityInfoDAO.queryAllActivityByType error", e);
            return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(), CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
        result.setData(resourceList);
        return result;
    }

    public ApiResult<Boolean> deleteGlobalActivity(long activityId) {
        try {
            GlobalActivityInfoDO globalActivityInfoDO = new GlobalActivityInfoDO();
            globalActivityInfoDO.setId(activityId);
            globalActivityInfoDO.setStatus(ActiveStatusEnums.DELETED.getStatus().intValue());
            globalActivityInfoDAO.updateStatus(globalActivityInfoDO);
            globalActivityExtendInfoDAO.deleteExtendByActivityId(activityId);
            return ApiResult.newSuccessResult(true);
        } catch (Exception e) {
            logger.error("deleteGlobalActivity error ", e);
            return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(),
                    CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    @Override
    public BaseDao<GlobalActivityInfoDO> getDao() {
        return this.globalActivityInfoDAO;
    }

    public ApiResult<List<GlobalActivityExtendInfoDO>> queryEffectExtendInfoList(ActivityExtendQueryDO activityExtendQueryDO) {
        Integer totalCount = 0;
        try {
            totalCount = globalActivityExtendInfoDAO.getEffectExtendInfoCount(activityExtendQueryDO);
        } catch (Exception e) {
            logger.error("globalActivityExtendInfoDAO.getEffectExtendInfoCount error,", e);
        }
        ApiResult<List<GlobalActivityExtendInfoDO>> result = new ApiResult<List<GlobalActivityExtendInfoDO>>();
        result.setTotalCount(totalCount);
        List<GlobalActivityExtendInfoDO> resourceList = null;
        try {
            resourceList = globalActivityExtendInfoDAO.getEffectExtendInfoList(activityExtendQueryDO);
        } catch (Exception e) {
            logger.error("globalActivityExtendInfoDAO.getEffectExtendInfoList error", e);
        }
        fillProperty(resourceList);
        result.setData(resourceList);
        return result;
    }

    private void fillProperty(List<GlobalActivityExtendInfoDO> resourceList) {

        if (CollectionUtils.isEmpty(resourceList)) {
            return;
        }
        ActiveSchemaEnum activeSchemaEnum = ActiveSchemaEnum.valueOf(resourceList.get(0).getActivityType());
        if (activeSchemaEnum == ActiveSchemaEnum.NEW_YANGTAO_INDEX_JINGXUAN) {
            List<Long> itemIdList = Lists.newArrayList();
            Map<Long, GlobalActivityExtendInfoDO> extendInfoDOMap = Maps.newHashMap();
            for (GlobalActivityExtendInfoDO globalActivityExtendInfoDO : resourceList) {
                itemIdList.add(globalActivityExtendInfoDO.getUnitId());
                extendInfoDOMap.put(globalActivityExtendInfoDO.getUnitId(), globalActivityExtendInfoDO);
            }
            ItemQueryDO itemQueryDO = new ItemQueryDO();
            itemQueryDO.setItemIdList(itemIdList);
            itemQueryDO.setPageSize(itemIdList.size());
            ApiResult<List<ItemDO>> itemListResult = itemReadManger.queryItem(itemQueryDO);
            if (!itemListResult.isSuccess()) {
                logger.error("获取商品信息失败！");
                return;
            }
            for (ItemDO itemDO : itemListResult.getData()) {
                GlobalActivityExtendInfoDO extendInfoDO = extendInfoDOMap.get(itemDO.getId());
                extendInfoDO.setContents(rebuildContent(activeSchemaEnum, extendInfoDO.getContents(), itemDO));
            }
        }


    }

    private String rebuildContent(ActiveSchemaEnum activeSchemaEnum, String contents, ItemDO itemDO) {
        if (activeSchemaEnum != ActiveSchemaEnum.NEW_YANGTAO_INDEX_JINGXUAN) {
            return contents;
        }
        Map<String, String> jsonMap = JSON.parseObject(contents, new TypeReference<Map<String, String>>() {
        });
        if (!jsonMap.containsKey("itemTitle")) {
            jsonMap.put("itemTitle", itemDO.getTitle());
        }
        if (!jsonMap.containsKey("itemPic")) {
            jsonMap.put("itemPic", itemDO.getPic());
        }
        return JSON.toJSONString(jsonMap);
    }

    @NeedOperateFlow(operateIdArgLocation = 3, operateFlowEnum = OperateFlowEnum.ACTIVITY)
    public ApiResult<Boolean> insertActivityExtendList(long activityId, List<GlobalActivityExtendInfoDO> activityExtendInfoDOList, Long loginUserId) {

        try {
            Date date = new Date();
            for (GlobalActivityExtendInfoDO globalActivityExtendInfoDO : activityExtendInfoDOList) {
                globalActivityExtendInfoDO.setGmtCreate(date);
                globalActivityExtendInfoDO.setGmtModified(date);
                globalActivityExtendInfoDO.setActivityId(activityId);
                globalActivityExtendInfoDAO.save(globalActivityExtendInfoDO);
            }
            return ApiResult.newSuccessResult(true);
        } catch (Exception e) {
            logger.error("globalActivityExtendInfoDAO.insertGlobalActivityExtendInfo error", e);
            return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(), CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    @NeedOperateFlow(operateIdArgLocation = 2, operateFlowEnum = OperateFlowEnum.ACTIVITY)
    public ApiResult<Boolean> deleteExtendInfo(Long extendId, Long loginUserId) {
        try {
            boolean success = globalActivityExtendInfoDAO.deleteExtend(extendId) > 0;
            if (success) {
                return ApiResult.newSuccessResult(true);
            } else {
                return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(), CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
            }
        } catch (Exception e) {
            logger.error("globalActivityExtendInfoDAO.deleteExtend error", e);
            return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(), CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    /**
     * 根据活动类型获取当前时间下的所有活动商品
     *
     * @param activityType
     * @return
     */
    public List<GlobalActivityExtendInfoDO> getCurrentActivityExtendList(int activityType) {
        List<GlobalActivityExtendInfoDO> currentActivityExtendList = globalActivityExtendInfoDAO.getCurrentActivityExtendList(activityType);
        fillProperty(currentActivityExtendList);
        return currentActivityExtendList;
    }

    /**
     * 分页 根据活动类型获取当前时间下的所有活动商品
     * @param extendInfoDO
     * @return
     */
    public List<GlobalActivityExtendInfoDO> getCurrentActivityExtendList(GlobalActivityExtendInfoDO extendInfoDO) {
        List<GlobalActivityExtendInfoDO> currentActivityExtendList = globalActivityExtendInfoDAO.getCurrentActivityExtendListWithPage(extendInfoDO);
        fillProperty(currentActivityExtendList);
        return currentActivityExtendList;
    }
}
